from django.db import models
from django.contrib.auth.models import User
from PIL import Image
# Create your models here.
from django.urls import reverse


class ArticleColumn(models.Model):
    """
    栏目
    """
    title = models.CharField(max_length=100, blank=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title


class ArticlePost(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    column = models.ForeignKey(ArticleColumn, null=True, blank=True, on_delete=models.CASCADE, related_name='article')
    title = models.CharField(max_length=100)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    update = models.DateTimeField(auto_now=True)
    total_view = models.PositiveIntegerField(default=0)  # 文章浏览量
    avatar = models.ImageField(upload_to='article/', blank=True)

    def get_absolute_url(self):
        return reverse('article:article_detail', args=[self.id])

    # 保存时处理图片
    def save(self, *args, **kwargs):
        # 调用原有的save()的功能
        article = super(ArticlePost, self).save(*args, **kwargs)
        # 固定宽度缩放图片的大小
        if self.avatar and not kwargs.get('update_fields'):
            image = Image.open(self.avatar)
            (x, y) = image.size
            new_x = 400
            new_y = int(new_x * (y / x))
            resized_image = image.resize((new_x, new_y), Image.ANTIALIAS)
            resized_image.save(self.avatar.path)
        return article

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return self.title
